<template>
  <div>
    <TopFilter ref="topFilter" :rows="2" :list="topFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle" />

    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      columnsRef="repair_workManage_repairDispatch_index"
      selectionType="single"
      :dataSource="tableDataList"
      :isMemoryPagination="true"
      :isExportExcel="canExportExcel"
      exportFileName="维修派工信息导出表.xlsx"
      :onRowSelectChange="list => (this.selectedTableRow = list)"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="handleTableDataChange"
    >
      <template slot="controls">
        <el-button size="small" type="primary" @click="roAssignAllClick">整单派工</el-button>
        <el-button size="small" type="primary" @click="roAssignClick">分项派工</el-button>

        <!-- <el-button size="small" type="primary">打印派工</el-button> -->
        <el-button size="small" type="primary" @click="closeAssignClick">完工验收</el-button>
        <!-- <el-button size="small" type="primary" @click="completedClick">{{ completedTatle }}</el-button> -->
        <!-- <el-button size="small" type="primary" @click="completedClick">竣工</el-button> -->
        <AjaxButton size="small" type="primary" :click="handleCompletedBtnClick">{{ selectedRowISCompleted ? '取消竣工' : '竣工' }}</AjaxButton>

        <!-- <multiuse-button v-if="completedTatle === '取消竣工'" size="small" type="primary" :auth-list="auths" auth-mark="/repair/workManage/repairDispatch/Cancelcompletion" @click="completedClick"
          >取消竣工
        </multiuse-button>  -->
      </template>
    </FilterTable>
    <Drawer :visible.sync="roAssignAll" :title="'整单派工'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <roAssignAllModel :roNo="selectedTableRow" :assignType="assignType" @close="closeDialog" />
    </Drawer>

    <Drawer :visible.sync="roAssign" :title="'分项派工'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <roAssignModel :roNo="selectedTableRow" :allUsers="this.allUsers" :assignType="assignType" @close="closeDialog" @completedClick="completedClick" />
    </Drawer>

    <BaseDialog :visible.sync="closeAssign" :title="'完工验收'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <closeAssignModel :roNo="selectedTableRow" @close="closeHandler" />
    </BaseDialog>

    <BaseDialog :visible.sync="itemPart" :title="'漆辅料'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <ItemPartModel :roNo="selectedTableRow" @close="closeHandler" />
    </BaseDialog>

    <BaseDialog :visible.sync="completed" :title="'竣工'" destroyOnClose width="450px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <completedModel :Mileage="selectedTableRow" @close="closeDialog" />
    </BaseDialog>

    <!-- 打印派工 -->
    <BaseDialog :visible.sync="showPrintForm" :title="'打印派工'" destroyOnClose width="450px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <PrintForm :roNo="roNo" :modelName="modelName" @close="closePrintForm" />
    </BaseDialog>
    <!-- <el-button size="small" type="primary" @click="roAssignExportData">导出</el-button> -->
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import {
  queryRepairAssign,
  updateRepairAssignTag,
  updateRepairAssignPartTag,
  queryRepair,
  maintainRepairBack,
  roAssignExportExcel,
  queryFinished,
  checkProject,
  maintainRepairNew,
  maintainRepairBackNew
} from '@/api/repair/repairAssign/repairAssign';
import { getDealerUser } from '@/api/repair/repairReception/customer';
import ItemPartModel from './ItemPartModel';
import { searchRoleByCode } from '@/api/common/empSelect/index';
import dictCode from '@/utils/dictCode';
import completedModel from './completedModel';
import roAssignAllModel from './roAssignAllModel';
import roAssignModel from './roAssignModel';
import closeAssignModel from './closeAssignModel';
import PrintForm from './printForm';
import { exportExcelFile, notifyAction, confirmAction } from '@/utils/index';
import moment from 'moment';
import { authority } from '@/utils/authMixin';
import { getWxlxSelect } from '@/api/repair/repairReception/customer';
import { findAllRepair } from '@/api/repair/basicParameters';
import { menuUserAction } from '@/api/repair/repairReception/repairBusinessManger';
import _ from 'lodash';

export default {
  name: 'repairAssign',
  components: {
    ItemPartModel,
    completedModel,
    roAssignAllModel,
    roAssignModel,
    closeAssignModel,
    PrintForm
  },
  mixins: [dictionary, authority],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      fetchParams: { xhrAbort: true },
      columns: this.createTableColumns(),
      fetchApi: queryRepairAssign,
      itemPart: false,
      completed: false,
      roAssignAll: false,
      roAssign: false,
      closeAssign: false,
      waitTag: 10041001,
      partTag: 10041001,
      repairAssignTagTiatle: '等待答复',
      repairAssignPartTatle: '等待配件',
      completedTatle: '竣工',
      selectedTableRow: [],
      showPrintForm: false,
      roNo: null,
      tableDataList: [], // table列表数据
      modelName: null,
      assignType: '',
      allUsers: [],
      canExportExcel: false, // 是否能够导出
      syncTableDataList: [], // 同步储存的table数据
      mainTableIsFetching: false // 主列表是否在加载中
    };
  },
  computed: {
    // 选中的行项是否竣工（控制按钮显示字样及后续业务逻辑）
    selectedRowISCompleted() {
      return this.selectedTableRow[0] && this.selectedTableRow[0].COMPLETE_TAG == 10041001;
    }
  },
  watch: {
    selectedTableRow: function(newVal, oldVal) {
      if (newVal.length > 0) {
        this.repairAssignTagTiatle = newVal[0].WAIT_INFO_TAG && newVal[0].WAIT_INFO_TAG === 10041001 ? '取消等待答复' : '等待答复';
        this.waitTag = newVal[0].WAIT_INFO_TAG && newVal[0].WAIT_INFO_TAG === 10041001 ? 10041001 : 10041002;
        this.repairAssignPartTatle = newVal[0].WAIT_PART_TAG && newVal[0].WAIT_PART_TAG === 10041001 ? '取消等待配件' : '等待配件';
        this.partTag = newVal[0].WAIT_PART_TAG && newVal[0].WAIT_PART_TAG === 10041001 ? 10041001 : 10041002;
        this.completedTatle = newVal[0].COMPLETE_TAG && newVal[0].COMPLETE_TAG === 10041001 ? '取消竣工' : '竣工';
      }
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    // this.serviceConsultant();
    this.getSystemDefaultValueInfo();
    this.serviceAdvisor();
    this.initTableSelectData();
    this.getWxtypeSelect();
    // this.queryMainTableData();
    this.queryMenuUserAction();
  },
  methods: {
    async getSystemDefaultValueInfo() {
      // 北汽仅派工到人 hxj 2020-12-29
      // let resRepair = await findAllRepair();
      // this.assignType = String(resRepair.data['9505']); // group-派工到班组，major - 派工到人
      this.assignType = 'major';
    },
    // 查询导出按钮权限
    async queryMenuUserAction() {
      let res = await menuUserAction();
      if (res.resultCode == 200) {
        res.data.forEach(item => {
          if (item.actionUrl == '/repair/workManage/repairDispatch') {
            this.canExportExcel = true;
          }
        });
      }
    },
    // 查询条件
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'LICENSE',
          placeholder: '请输入车牌号'
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'SERVICE_ADVISOR',
          placeholder: '请选择服务顾问',
          itemList: [],
          filterable: true
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'RO_NO',
          placeholder: '请输入工单号'
        },
        {
          type: 'SELECT',
          label: '日期类型',
          fieldName: 'QUERY_TYPE',
          placeholder: '请选择日期类型',
          itemList: [
            { text: '工单开单日期', value: '1' },
            { text: '预交车时间', value: '2' }
          ],
          initialValue: '1',
          rules: [{ required: true, message: '请选日期类型', trigger: 'change' }]
        },
        {
          type: 'RANGE_DATE',
          label: '选择日期',
          fieldName: 'BEGIN_TIME|END_TIME',
          initialValue: [
            moment(new Date())
              .subtract(6, 'month')
              .format('YYYY-MM-DD'),
            moment(new Date()).format('YYYY-MM-DD')
          ],
          valueFormat: 'yyyy-MM-dd',
          rules: [{ required: true, message: '请选日期', trigger: 'change' }]
        },
        {
          type: 'SELECT',
          label: '派工状态',
          fieldName: 'ASSIGN_STATUS',
          placeholder: '请选择派工状态',
          itemList: this.createDictList('8059')
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'REPAIR_TYPE_CODE',
          placeholder: '请选择维修类型',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '是否竣工',
          fieldName: 'COMPLETE_TAG',
          placeholder: '请选择是否竣工',
          itemList: this.createDictList('1004')
        }
        // {
        //   type: 'SELECT',
        //   label: '工单状态',
        //   fieldName: 'RO_STATUS',
        //   placeholder: '请选择工单状态',
        //   itemList: this.createDictList('8049')
        // }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '工单号',
          dataIndex: 'RO_NO',
          sorter: true,
          filter: true,
          width: 160,
          filterType: 'input'
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          filter: true,
          width: 150,
          filterType: 'input'
        },
        {
          title: '品牌',
          dataIndex: 'BRAND',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'SERIES',
          sorter: true,
          filter: true,
          width: 160,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'MODEL',
          sorter: true,
          filter: true,
          width: 260,
          filterType: 'input'
        },
        // {
        //     title: '工单类型',
        //     dataIndex: 'RO_TYPE',
        //     sorter: true,
        //     filter: true,
        //     render: props =>{
        //         return <span>{this.createDictText(props.row.RO_TYPE,'8068')}</span>
        //     }
        // },
        {
          title: '维修类型',
          dataIndex: 'REPAIR_TYPE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '派工状态',
          dataIndex: 'ASSIGN_STATUS',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8059'),
          dictItems: this.createDictList('8059')
        },
        {
          title: '服务顾问',
          dataIndex: 'SERVICE_ADVISOR',
          sorter: true,
          filter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterItems: [],
          filterType: 'checkbox'
        },
        {
          title: '故障描述',
          dataIndex: 'RO_TROUBLE_DESC',
          sorter: true,
          filter: true,
          showOverflowTooltip: true,
          filterType: 'input'
        },
        // {
        //   title: '锁定人',
        //   dataIndex: 'LOCK_USER',
        //   sorter: true,
        //   filter: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: [],
        //   filterItems: [],
        //   filterType: 'checkbox'
        // },
        {
          title: '工单开单日期',
          dataIndex: 'RO_CREATE_DATE',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        // {
        //   title: '指定技师',
        //   dataIndex: 'CHIEF_NAME',
        //   sorter: true,
        //   filter: true,
        //   editable: false,
        //   editType: 'select',
        //   editItems: []
        // },
        {
          title: '预交车时间',
          dataIndex: 'END_TIME_SUPPOSED',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '试车员',
          dataIndex: 'TEST_NAME',
          editable: false,
          editType: 'select',
          editItems: [],
          sorter: true,
          filter: true,
          filterItems: [],
          filterType: 'checkbox'
        },
        {
          title: '工单状态',
          dataIndex: 'RO_STATUS',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8049'),
          dictItems: this.createDictList('8049')
        },

        {
          title: '是否竣工',
          dataIndex: 'COMPLETE_TAG',
          sorter: true,
          filter: true,
          filterType: 'radio',
          filterItems: this.createDictList('1004'),
          dictItems: this.createDictList('1004')
        },
        {
          title: '进厂行驶里程',
          dataIndex: 'IN_MILEAGE',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '出厂行驶里程',
          dataIndex: 'OUT_MILEAGE',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '车主',
          dataIndex: 'OWNER_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人',
          dataIndex: 'DELIVERER',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人电话',
          dataIndex: 'DELIVERER_PHONE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人手机',
          dataIndex: 'DELIVERER_MOBILE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '班组',
          dataIndex: 'WORKGROUP_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修人',
          dataIndex: 'TECHNICIAN',
          sorter: true,
          filter: true,
          filterType: 'input',
          editItems: [],
          filterItems: [],
          render: props => {
            let str = '';
            if (props.row.TECHNICIAN) {
              let editItems = this.columns.find(x => x.dataIndex === 'TECHNICIAN').editItems;
              if (!editItems) {
                return <span>{props.row.TECHNICIAN}</span>;
              }
              if (props.row.TECHNICIAN.includes(',')) {
                let data = props.row.TECHNICIAN.split(',');
                data.forEach((val, index) => {
                  let name = '';
                  let item = editItems.find(x => x.value == val);
                  name = item ? item.text : val;
                  str = str + `${name},`;
                });
                str = str.substring(0, str.length - 1);
                // console.log(str);
              } else {
                let item = editItems.find(x => x.value == props.row.TECHNICIAN);
                str = item ? item.text : props.row.TECHNICIAN;
                // console.log(str);
              }
            }
            return <span>{str}</span>;
          }
        },

        {
          title: '终检人',
          dataIndex: 'FINISH_NAME',
          editable: false,
          editType: 'select',
          editItems: [],
          sorter: true,
          filter: true,
          filterItems: [],
          filterType: 'checkbox'
        }
      ];
    },
    // 查询table主数据
    async queryMainTableData() {
      if (this.mainTableIsFetching) return this.$notify.info({ title: '提示信息', message: '数据请求中，请耐心等待' });
      this.mainTableIsFetching = true;
      let formParams = await this.$refs.topFilter.GET_FORM_DATA();
      this.$refs.table.START_LOADING();
      try {
        let res = await this.fetchApi(formParams[1] || {});
        if (res.resultCode == 200) {
          this.tableDataList = res.data;
        }
      } catch (err) {
        console.log(err, '查询table主数据失败');
      } finally {
        this.mainTableIsFetching = false;
        this.$refs.table.STOP_LOADING();
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val, { xhrAbort: false });
      this.completedTatle = '竣工';
      this.queryMainTableData();
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    async initTableSelectData() {
      // const res = await searchRoleByCode({ role: '' });
      const res = await getDealerUser();
      this.allUsers = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      // this.columns.find(x => x.dataIndex === 'LOCK_USER').editItems = this.allUsers;
      this.columns.find(x => x.dataIndex === 'TEST_NAME').editItems = this.allUsers;
      this.columns.find(x => x.dataIndex === 'FINISH_NAME').editItems = this.allUsers;
      this.columns.find(x => x.dataIndex === 'TECHNICIAN').editItems = this.allUsers;
      // this.columns.find(x => x.dataIndex === 'LOCK_USER').filterItems = this.allUsers;
      this.columns.find(x => x.dataIndex === 'TEST_NAME').filterItems = this.allUsers;
      this.columns.find(x => x.dataIndex === 'FINISH_NAME').filterItems = this.allUsers;
      this.columns.find(x => x.dataIndex === 'TECHNICIAN').filterItems = this.allUsers;
      // let technician = { role: dictCode.TECHNICIAN };
      // const technicianRes = await searchRoleByCode(technician);
      // console.log('技师信息', technicianRes);
      // this.columns.find(x => x.dataIndex === 'CHIEF_NAME').editItems = technicianRes.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    async repairAssignTag() {
      if (this.checkOut() && this.chekcComplete()) {
        let res = await updateRepairAssignTag(this.selectedTableRow[0].RO_NO, this.waitTag);
        if (res.resultCode == 200) {
          this.refreshTable();
        }
      }
    },
    async repairAssignPart() {
      if (this.checkOut() && this.chekcComplete()) {
        let res = await updateRepairAssignPartTag(this.selectedTableRow[0].RO_NO, this.partTag);
        if (res.resultCode == 200) {
          this.refreshTable();
        }
      }
    },
    async roAssignAllClick() {
      if (this.checkOut() && this.chekcComplete()) {
        let res = await queryRepair(this.selectedTableRow[0].RO_NO);
        if (res.data == 1) {
          this.roAssignAll = true;
        } else if (res.data == 0) {
          this.$notify.error({ title: '提示信息', message: '此工单不存在需要派工的维修项目!' });
        }
      }
    },
    async roAssignClick() {
      if (this.checkOut() && this.chekcComplete()) {
        let res = await queryRepair(this.selectedTableRow[0].RO_NO);

        if (res.data == 1) {
          this.roAssign = true;
        } else if (res.data == 0) {
          this.$notify.error({ title: '提示信息', message: '此工单不存在需要派工的维修项目!' });
        }
      }
    },
    closeAssignClick() {
      if (this.checkOut() && this.chekcComplete()) {
        if (this.selectedTableRow[0].ASSIGN_STATUS != 80591003) {
          this.$notify.error({ title: '提示信息', message: '请先派工!' });
        } else if (this.selectedTableRow[0].COMPLETE_TAG == 10041001) {
          this.$notify.warning({ title: '提示信息', message: '工单已竣工，不能进行此操作!' });
        } else {
          this.closeAssign = true;
        }
      }
    },
    itemPartClick() {
      if (this.checkOut() && this.chekcComplete()) this.itemPart = true;
    },
    checkOut() {
      if (this.selectedTableRow.length <= 0) {
        this.$notify.error({ title: '提示信息', message: '请先选择数据!' });
        return false;
      } else {
        return true;
      }
    },
    async completedClick() {
      this.checkOut();
      let ref = await checkProject(this.selectedTableRow[0].RO_NO);
      if (this.checkOut()) {
        ref.data == '1'; // 时候维修项目都是不修项目可以直接竣工
        if (ref.data == '1' && this.selectedTableRow[0].COMPLETE_TAG == 10041002) {
          this.completed = true;
        } else {
          if (this.selectedTableRow[0].ASSIGN_STATUS == 80591003) {
            if (this.selectedTableRow[0].COMPLETE_TAG == 10041002) {
              let res = await queryFinished(this.selectedTableRow[0].RO_NO).then(res => {
                if (res.data == '1') {
                  this.$notify.warning({ title: '提示信息', message: '此工单存在未入账配件，不能竣工 !' });
                } else {
                  this.completed = true;
                }
              });
            }
            // else {
            //   await maintainRepairBack(this.selectedTableRow[0].RO_NO);
            //   this.refreshTable();
            // }
          } else {
            this.$notify.warning({ title: '提示信息', message: '存在未派工的项目，不能竣工!' });
            return;
          }
        }
        // 状态是竣工
        if (this.selectedTableRow[0].COMPLETE_TAG == 10041001) {
          await maintainRepairBack(this.selectedTableRow[0].RO_NO);
          this.refreshTable();
          this.completedTatle = '竣工';
        }
      }
    },
    refreshTable() {
      // this.fetchParams = Object.assign({}, this.fetchParams); // 刷新表格
      this.queryMainTableData();
    },
    // 售前人员接口数据
    // async serviceConsultant() {
    //   let technician = { role: dictCode.TECHNICIAN }; // 指定技师
    //   const technicianRes = await searchRoleByCode(technician);
    //   this.columns.find(item => item.dataIndex === 'CHIEF_NAME').editItems = technicianRes.data.map(x => ({ text: x.employeeName, value: x.userId }));
    // },
    async serviceAdvisor() {
      let testDrive = { role: dictCode.SERVICE_CONSULTANT };
      const res = await searchRoleByCode(testDrive);
      // 获取portal的参数
      let allCookie = document.cookie.split(';');
      let user = '';
      allCookie.forEach(x => {
        if (x.indexOf('userId') > -1) {
          user = x.split('=')[1];
        }
      });
      this.topFilterList.find(x => x.fieldName === 'SERVICE_ADVISOR').itemList = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      for (const x of res.data) {
        if (x.userId + '' == user + '') {
          // 因为cookie取回是int值
          this.topFilterList.find(x => x.fieldName === 'SERVICE_ADVISOR').initialValue = user;
          break; // 取当前服务顾问
        }
      }
      this.columns.find(x => x.dataIndex === 'SERVICE_ADVISOR').editItems = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      this.columns.find(x => x.dataIndex === 'SERVICE_ADVISOR').filterItems = res.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    chekcComplete() {
      return true;
      // if (this.selectedTableRow[0].COMPLETE_TAG == 10041002) {
      //   return true;
      // } else {
      //   this.$notify.error({ title: '提示信息', message: '该工单已竣工，不能进行此操作!' });
      //   return false;
      // }
    },
    closeHandler(val) {
      if (val) {
        this.refreshTable();
      }
      this.itemPart = false;
      this.completed = false;
      this.closeAssign = false;
    },
    closeDialog(val) {
      // 刷新单条数据
      if (val) {
        this.refeshSingleTableData(val);
      }
      this.roAssign = false;
      this.completed = false;
      this.roAssignAll = false;
      // this.refreshTable();
    },
    openPrintForm() {
      if (this.selectedTableRow.length == 1) {
        this.roNo = this.selectedTableRow[0].RO_NO;
        this.modelName = this.selectedTableRow[0].MODEL;
        this.showPrintForm = true;
      } else {
        this.$notify.error({ title: '提示信息', message: '请选择一条表格数据!' });
      }
    },
    closePrintForm() {
      this.showPrintForm = false;
    },

    // 导出
    roAssignExportData() {
      roAssignExportExcel(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res, '维修派工  ');
      });
    },
    // 获取维修项目类型
    async getWxtypeSelect() {
      const res = await getWxlxSelect();
      this.topFilterList.find(x => x.fieldName === 'REPAIR_TYPE_CODE').itemList = res.data.map(x => ({
        value: x.REPAIR_TYPE_CODE + '',
        text: x.REPAIR_TYPE_NAME
      }));
    },
    // 同步储存table数据
    handleTableDataChange(e) {
      this.syncTableDataList = e;
    },
    // 刷新table单条数据
    async refeshSingleTableData(uid) {
      console.log(uid);
      let target = this.syncTableDataList.find(x => x._uid == uid);
      if (target) {
        let res = await this.fetchApi({
          RO_NO: target.RO_NO
        });
        if (res.resultCode == 200 && res.data.length) {
          // 手动处理空数据(修改单条不会触发table格式化，防止更新后的数据出现null)
          for (let item in res.data[0]) {
            res.data[0][item] = _.isNil(res.data[0][item]) ? '' : res.data[0][item];
          }
          Object.assign(target, res.data[0]);
        }
      }
    },
    // 竣工取消竣工重构逻辑
    async handleCompletedBtnClick() {
      if (!this.selectedTableRow.length) return notifyAction('请选择需要竣工的工单', 'warning');
      console.log();
      if (!this.selectedRowISCompleted) {
        // 竣工逻辑
        try {
          await confirmAction('此操作将竣工该工单，是否继续？');
          let res = await maintainRepairNew({ roNo: this.selectedTableRow[0].RO_NO });
          if (res.resultCode == 200) {
            notifyAction('工单竣工完成', 'success');
            this.refreshTable();
          }
        } catch (err) {
          console.log(err, '竣工失败');
        }
      } else {
        // 取消竣工逻辑
        try {
          await confirmAction('此操作将取消竣工该工单，是否继续？');
          let res = await maintainRepairBackNew({ roNo: this.selectedTableRow[0].RO_NO });
          if (res.resultCode == 200) {
            notifyAction('工单取消竣工完成', 'success');
            this.refreshTable();
          }
        } catch (err) {
          console.log(err, '取消竣工失败');
        }
      }
    }
  }
};
</script>

<style lang="less" scoped></style>
